import type { FormItemDto } from '../types'
import Upload from '@/components/file/Upload'
import { divide } from 'lodash'
import { QuestionOutlined } from '@ant-design/icons-vue'
import { AutoComplete, Button, ButtonGroup, Cascader, Checkbox, CheckboxGroup, DatePicker, Input, InputNumber, Popover, Radio, RadioButton, RadioGroup, RangePicker, SelectOption, Switch, Textarea, TimePicker, TreeSelect, type AutoCompleteProps, type InputProps } from 'ant-design-vue'
import type { CascaderOptionType } from 'ant-design-vue/es/cascader'
import PrefixSelect from '@/components/prefix-select/Index'
import PrefixDatePicker from '@/components/prefix-date-picker/Index'
import PrefixRangePicker from '@/components/prefix-range-picker/Index'
import type { Dayjs } from 'dayjs'
import PrefixAutoComplete from '@/components/prefix-auto-complete/Index'
import type { DefaultOptionType } from 'ant-design-vue/es/vc-tree-select/TreeSelect'
import AreaSelect from '@/components/area-select/Index'
export function checkbox(data: FormItemDto) {
    return <>
        {data?.params?.prefix ?? undefined}
        <Checkbox v-model={data.value} disabled={data.readonly}
            onChange={data.callback?.change ?? undefined} >{data.params?.label}</Checkbox>
        {data?.params?.suffix ?? undefined}
    </>
}

export function select(data: FormItemDto) {
    return <PrefixSelect
        v-model:value={data.value}
        show-search
        disabled={data.readonly}
        prefixString={data.prefix ? data.name : undefined}
        mode={(data.params?.multiple || data.multiple) ? 'multiple' : undefined}
        allowClear={data.params && Reflect.has(data.params, 'clearable') ? data.params.clearable : true}
        onSearch={data.params?.method}
        loading={data.params?.loading}
        class={data.class + ' w-full'}
        labelInValue={data.params?.labelInValue}
        filterOption={false}
        placeholder={data.placeholder || '请选择'}
        notFoundContent={data.params?.noDataText || '无数据'}
        default-first-option={data.params?.defaultFirstOption}
        maxTagCount={data.params?.maxTagCount}
        onChange={data.callback?.change ?? undefined}
        onFocus={data.callback?.focus ?? undefined}
        onBlur={data.callback?.blur ?? undefined}
        options={data.options}   
    >
    </PrefixSelect>
}

export function treeSelect(data: FormItemDto) {
    return <TreeSelect v-model:value={data.value}
        showSearch={data.params?.showSearch ?? true}
        placeholder={data.placeholder || '请选择'}
        allowClear={data.params && Reflect.has(data.params, 'clearable') ? data.params.clearable : true}
        class={data.class + ' w-full'}
        treeData={data.options as DefaultOptionType[]}
        treeNodeFilterProp={data.params?.label || 'value'}
        treeNodeLabelProp={data.params?.label || 'label'}
        onChange={data.callback?.change ?? undefined}
    ></TreeSelect>
}

export function cascader(data: FormItemDto) {
    return (
        <Cascader
            v-model={data.value}
            disabled={data.readonly}
            class={data.class + ' w-full'}
            options={data.options as CascaderOptionType[]}
            popper-class={data.params?.popperClass}
        ></Cascader>
    )
}

export function checkboxGroup(data: FormItemDto) {
    return <CheckboxGroup v-model:value={data.value} disabled={data.readonly} class={data.class}
        onChange={data.callback?.change ?? undefined}
    >

        {data?.options?.map(item => {
            return <Checkbox value={item.value} disabled={item.disabled} >{item.label}</Checkbox>
        }
        )}
    </CheckboxGroup>
}

export function radioGroup(data: FormItemDto) {
    return <div>
        {data.params?.prepend}
        <div class="flex items-center">
            {data.params?.prefix}
            <RadioGroup v-model:value={data.value} disabled={data.readonly} class={`${data.class} !text-14px px-12`}
                onChange={data.callback?.change ?? undefined}
            >
                {
                    data?.options?.map(item => {
                        if (data.params?.buttonLayout) {
                            return <RadioButton disabled={item.disabled} value={item.value}>{item.label}</RadioButton>
                        } else {
                            return <Radio disabled={item.disabled} class={data?.params?.radioClassName} value={item.value}>{item.label}</Radio>
                        }
                    })
                }
                {
                    (Array.isArray(data?.params?.tips) ? data?.params?.tips.length : data?.params?.tips) && tips({
                        name: '',
                        element: '',
                        params: {
                            content: () => {
                                const list = Array.isArray(data.params.tips) ? data.params.tips : [data.params.tips]
                                return list.map((item: string, idx: number) => <div>{idx + 1}.{item}</div>)
                            }
                        }
                    })
                }
            </RadioGroup>
            {data.params?.suffix}
        </div>
        {data.params?.append}
    </div>
}

function handleBlur($event: FocusEvent, data: FormItemDto) {
    data.value = typeof data.value === 'string' ? data?.value.trim() : data.value
    data.callback?.blur && data.callback.blur($event)
}

export function input(data: FormItemDto) {
    return <Input
        v-model:value={data.value}
        disabled={!!data.readonly}
        class={data.class}
        prefix={data.prefix}
        suffix={data.suffix}
        placeholder={data.placeholder || '请输入'}
        type={data.type as InputProps['type']}
        allowClear={data.params?.clearable || true}
        maxlength={data.params?.maxlength}
        show-word-limit={data.params?.showWordLimit}
        auto-complete={data.params?.autocomplete}
        autocomplete={data.params?.autocomplete}
        onChange={data.callback?.change ?? undefined}
        onFocus={data.callback?.focus ?? undefined}
        onBlur={($event) => handleBlur($event, data)}
        onInput={data.callback?.input ?? undefined}
        v-slots={{
            addonAfter: data.params?.append ? () => {
                if (typeof data.params.append === 'string') {
                    return data.params.append
                } else if (typeof data.params.append === 'function') {
                    return data.params.append()
                }
            } : undefined,
            addonBefore: data.params?.prepend ? () => {
                if (typeof data.params.prepend === 'string') {
                    return data.params.prepend
                } else if (typeof data.params.prepend === 'function') {
                    return data.params.prepend()
                }
            } : undefined,
            prefix: data.params?.prefix ? () => {
                if (typeof data.params.prefix === 'string') {
                    return data.params.prefix
                } else if (typeof data.params.prefix === 'function') {
                    return data.params.prefix()
                }
            } : undefined,
            suffix: data.params?.suffix ? () => {
                if (typeof data.params.suffix === 'string') {
                    return data.params.suffix
                } else if (typeof data.params.suffix === 'function') {
                    return data.params.suffix()
                }
            } : undefined,

        }}
    />
}

export function autoComplete(data: FormItemDto) {
    return <PrefixAutoComplete
        v-model:value={data.value}
        prefixString={data.prefix ? data.name : undefined}
        disabled={!!data.readonly}
        class={data.class}
        placeholder={data.placeholder || '请输入'}
        allowClear={data.params?.clearable ?? true}
        onSearch={data.params?.method}
        onChange={data.callback?.change ?? undefined}
        onFocus={data.callback?.focus ?? undefined}
        onBlur={data.callback?.blur ?? undefined}
        options={data.options}
    />
}



export function inputNumber(data: FormItemDto) {
    return <>
        <InputNumber
            v-model:value={data.value}
            disabled={data.readonly}
            class={data.class + ' !w-full'}
            step={data?.params?.step || 1}
            min={data?.params?.min === 'undefined' ? -Infinity : data.params?.min}
            max={data?.params?.max === 'undefined' ? Infinity : data.params?.max}
            precision={data?.params?.precision}
            controls={data?.params?.controls}
            controls-position={data?.params?.controlsPosition}
            step-strictly={data?.params?.stepStrictly}
            value-on-clear={data?.params?.valueOnClear}
            style= {{ width: '100%' }}
            placeholder={data.placeholder}
            onChange={data.callback?.change ?? undefined}
            onFocus={data.callback?.focus ?? undefined}
            onBlur={data.callback?.blur ?? undefined}
            onInput={data.callback?.input ?? undefined}
        />
        {data.params?.after && <span class="ml-12">{data.params.after}</span>}
        {
            data.params?.prompt && <span class="ml-12" style={data.params?.promptColor ? `color:${data.params.promptColor}` : ''}>{data.params.prompt}</span>
        }
        {

            (Array.isArray(data?.params?.tips) ? data?.params?.tips.length : data?.params?.tips) && tips({
                name: '',
                element: '',
                value: '',
                class: 'ml-12 align-middle',
                params: {
                    content: () => {
                        const list = Array.isArray(data.params.tips) ? data.params.tips : [data.params.tips]
                        if (list.length === 1) return <div>{list[0]}</div>
                        return list.map((item: string, idx: number) => <div>{idx + 1}.{item}</div>)
                    }
                }
            })
        }


    </>
}

export function datetime(data: FormItemDto) {
    /*     console.log(data.value, '=== data.value ==');
        debugger; */
    return <PrefixDatePicker
        v-model:value={data.value}
        disabled={data.readonly}
        placeholder={data.placeholder || '请选择'}
        prefix={data.prefix ? data.name : undefined}
        picker={data.type || data.params?.type || 'date'}
        class={data.class + ' !w-full'}
        format={data.params?.format}
        disabled-date={(value: string) => {
            if (data.params && typeof (data.params.disabledDate) === 'function') {
                return data.params.disabledDate(value)
            }
            if (data.params && data.params.maxDateTime && data.params.minDateTime) { 
                return new Date(value).getTime() > new Date(data.params.maxDateTime).getTime() || new Date(value).getTime() < new Date(data.params.minDateTime).getTime()
            }
            if (data.params && data.params.maxDateTime) {
                return new Date(value).getTime() > new Date(data.params.maxDateTime).getTime()
            }
            if (data.params && data.params.minDateTime) {
                return new Date(value).getTime() < new Date(data.params.minDateTime).getTime()
            }
            return false
        }}
        unlink-panels
        popper-class={data.params?.popperClass}
        allowClear={data.params?.clearable ?? true}
        default-time={data.params?.defaultTime}
        default-value={data.params?.defaultValue}
        value-format={data.params?.valueFormat || 'YYYY-MM-DD HH:mm:ss'}
        presets={data.params?.presets}
        onChange={data.callback?.change ?? undefined} 
        calendar-change={data.callback?.change ?? undefined}
    />
}

export function rangePicker(data: FormItemDto) {
    return <PrefixRangePicker 
        v-model:value={data.value}
        disabled={data.readonly}
        picker={data.params?.picker ?? 'date'}
        prefix={data.prefix ? data.name : undefined}
        format={data.params?.format ?? 'YYYY-MM-DD'}
        valueFormat={data.params?.valueFormat ?? 'YYYY-MM-DD'}
        onChange={data.callback?.change ?? undefined}
    />
}

export function timePicker(data: FormItemDto) {
    return <TimePicker
        v-model:value={data.value}
        disabled={data.readonly}
        placeholder={data.placeholder || '请选择'}
        is-range={data.params?.isAange || false}
        class={data.class + ' !w-full'}
        value-format={data.params?.valueFormat || 'YYYY-MM-DD HH:mm:ss'}
        // onChange={data.callback?.change ?? undefined} 
        // onFocus={data.callback?.focus ?? undefined}
        // onBlur={data.callback?.blur ?? undefined}
    ></TimePicker>
}

export function textarea(data: FormItemDto) {
    return <Textarea v-model:value={data.value} disabled={data.readonly} class={data.class} placeholder={data.placeholder || '请输入'}
        maxlength={data.params?.maxlength}
        autosize={data.params?.autosize}
        show-word-limit={data.params?.showWordLimit}
        onChange={data.callback?.change ?? undefined}
        onFocus={data.callback?.focus ?? undefined}
        onBlur={data.callback?.blur ?? undefined}
    />
}

export function button(data: FormItemDto) {
    return <Button
        class={data.class}
        disabled={data.readonly}
        type={data.params?.type}
        loading={data.params?.loading}
        onClick={data.callback?.click ?? undefined}
        icon={data.params?.icon}
    >
        {data.value || data.name}
    </Button>
}

export function buttonGroup(data: FormItemDto) {
    return <ButtonGroup
        class={data.class}
    >
        {
            Array.isArray(data.params?.button) && data.params.button.map((item: FormItemDto) => {
                return button(item)
            })
        }
    </ButtonGroup>
}

export function elSwitch(data: FormItemDto) {
    return <Switch
        v-model:checked={data.value}
        class="mb-2"
        style={data?.params?.style}
        disabled={data.readonly}
        checkedValue={data?.params?.activeValue || 'Y'}
        unCheckedValue={data?.params?.inactiveValue === undefined ? 'N' : data?.params?.inactiveValue}
        checkedChildren={data?.params?.activeText}
        unCheckedChildren={data?.params?.inactiveText}
        onChange={data.callback?.change ?? undefined} 
    />
}

export function tips(data: FormItemDto) {
    return <Popover
        placement={data.params?.placement || 'right'}
        title={data.params?.title || ''}
        trigger="hover"
        v-slots={{
            reference: () => {
                return <el-icon class={`${data.class} cursor-pointer`} size="var(--text-lg)" color="var(--blue)"><QuestionOutlined /></el-icon>
            },
            default: () => {
                if (typeof (data.params.content) === 'function') {
                    return data.params.content()
                } else {
                    return data.params.content || ''
                }
            }
        }}
    >
    </Popover>
}

export function upload(data: FormItemDto) {
    return <>
        <Upload
            class={data.params?.class?.join(' ')}
            v-model={data.value}
            params={data.params}
            multiple={(data.multiple as boolean) || false}
        >
        </Upload>
        {data?.params?.suffix ?? undefined}
    </>
}

export function areaSelect(data: FormItemDto) {
    return <>
        <AreaSelect
            v-model:value={data.value}
            multiple={data.params?.multiple || false}
        />
    </>
}

export function empty(data: FormItemDto) {
    return <div>
        { data.prefix }
    </div>
}

export default {
    input,
    inputNumber,
    autoComplete,
    textarea,
    select,
    switch: elSwitch,
    checkbox,
    checkboxGroup,
    radioGroup,
    button,
    buttonGroup,
    datetime,
    timePicker,
    empty,
    upload,
    cascader,
    rangePicker,
    treeSelect,
    areaSelect
}
